/*
 * Copyright 2008 CSC Consulting Group under the Apache License, 
 * Version 2.0 (the "License"); you may not use this file except in 
 * compliance with the License. You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable 
 * law or agreed to in writing, software distributed under the License is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language 
 * governing permissions and limitations under the License.
 */
package com.waw.memberMap.plugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import com.jivesoftware.community.JiveGlobals;

/**
 * This class provides a geocoding function, <em>getLocation</em> that employs Google's geocoding service.
 * This class was copied from the web - location forgotten.
 *
 * @see com.waw.memberMap.plugin.Location
 * 
 * @author Jim Tremlett
 */
public class GeoCoder {
	private final static String ENCODING = "UTF-8";
	/**
	 * This method finds the geocode location for an address using the Google geocoding service.
	 * @param address the address to geocode.
	 * @return a Location for the address.
	 * @throws IOException indicates a problem performing the geocodeing.
	 */
	public static Location getLocation(String address) throws IOException {
		String key = JiveGlobals.getJiveProperty(MemberMapConsts.GLOBAL_MMAP_KEY);
		BufferedReader in = new BufferedReader(new InputStreamReader(new URL(
				"http://maps.google.com/maps/geo?q="
						+ URLEncoder.encode(address, ENCODING)
						+ "&output=csv&key=" + key).openStream()));
		String line;
		Location location = null;
		int statusCode = -1;
		while ((line = in.readLine()) != null) {
			// Format: 200,6,42.730070,-73.690570
			statusCode = Integer.parseInt(line.substring(0, 3));
			if (statusCode == 200)
				location = new Location(line.substring("200,6,".length(), line
						.indexOf(',', "200,6,".length())), line.substring(line
						.indexOf(',', "200,6,".length()) + 1, line.length()));
		}
		if (location == null) {
			switch (statusCode) {
			case 400:
				throw new IOException("Bad Request");
			case 500:
				throw new IOException("Unknown error from Google Encoder");
			case 601:
				throw new IOException("Missing query");
			case 602:
				return null;
			case 603:
				throw new IOException("Legal problem");
			case 604:
				throw new IOException("No route");
			case 610:
				throw new IOException("Bad key");
			case 620:
				throw new IOException("Too many queries");
			}
		}
		return location;
	}
}
